#include "msgq.h"
#include "bank.h"
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

int msgid = 0;
MSG_CTOS ctos = {};
MSG_STOC stoc = {};

void transfer(void)
{
	char path[80] = {};
	char path2[80] = {};
	char path0[40] = ACCOUNT_PATH;
	
	sprintf(path,"%s%s.dat",path0,ctos.acc.id);
	sprintf(path2,"%s%s.dat",path0,ctos.acc.id2);
	
	int fd = open(path,O_RDWR);
	int ret = read(fd,&stoc.acc,sizeof(Account));
	close(fd);	
	if(0 == ret)
	{
		strcpy(stoc.info,"read1");
		puts(stoc.info);
		return;
	}
	stoc.acc.balance -= ctos.acc.balance;
	if(0 > stoc.acc.balance) 	
	{
		strcpy(stoc.info,"needmore");
		puts(stoc.info);
		return;
	}	
	if(0 != access(path2,F_OK))
	{
		strcpy(stoc.info,"vip");
		puts(stoc.info);
		return;
	}	
	fd = open(path,O_RDWR);
	ret = write(fd,&stoc.acc,sizeof(Account));
	close(fd);
	if(0 == ret)
	{
		strcpy(stoc.info,"write");
		puts(stoc.info);
		return;
	}	
	
	int fd2 = open(path2,O_RDWR);
	ret = read(fd2,&stoc.acc,sizeof(Account));
	close(fd2);
	if(0 == ret)
	{
		strcpy(stoc.info,"read2");
		puts(stoc.info);
		return;
	}
	stoc.acc.balance += ctos.acc.balance;
	fd2 = open(path2,O_RDWR);
	ret = write(fd2,&stoc.acc,sizeof(Account));
	close(fd2);
	if(0 == ret)
	{
		strcpy(stoc.info,"write2");
		puts(stoc.info);
		return;
	}		
	//此时stoc中是目标帐号的信息
	int fd3 = open(path,O_RDWR);
	ret = read(fd3,&stoc.acc,sizeof(Account));
	close(fd3);
	if(0 == ret)
	{
		perror("read3");
		return;
	}		
	strcpy(stoc.info,"success");
}

int main(int argc,const char* argv[])
{
	printf("argv %s\n",argv[0]);
	msgid = get_msg(ACCOUNT_PATH,SUBP_CNT);
	
	for(;;)
	{
		recv_msg(msgid,&ctos,sizeof(MSG_CTOS),MSGTY_TRANSFER);
		transfer();
		stoc.type = ctos.return_type;
		send_msg(msgid,&stoc,sizeof(MSG_STOC));
	}	
}
